﻿using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;

namespace BizElements.Core
{
    static class SqlItemUtil
    {
        #region CleanParameterName.

        static readonly Regex allowedCharsInParameterName = new Regex("^[a-zA-Z_0-9]$");

        internal static string CleanParameterName(string dirtyName)
        {
            StringBuilder cleanName = new StringBuilder(dirtyName.Length);
            foreach (char dirtyPart in dirtyName)
            {
                bool isNotDirty = allowedCharsInParameterName.IsMatch(dirtyPart.ToString());
                if (isNotDirty)
                    cleanName.Append(dirtyPart);
            }

            return cleanName.ToString();
        }

        #endregion

        #region TryDetermineSubQueryDataType.

        internal static void TryDetermineSubQueryDataType(SelectStatement query, out Type dataType, out DbType dbType)
        {
            // Automatically determine data type if possible.
            if (query.SelectList.Count == 1)
            {
                SelectItem firstItem = query.SelectList[0];
                if (firstItem.ItemType == SqlItemType.Column)
                {
                    IDbColumn field = (IDbColumn)firstItem.Item;
                    dataType = field.DataType;
                    dbType = field.DbType;
                }
                else if (firstItem.ItemType == SqlItemType.Function)
                {
                    Function function = (Function)firstItem.Item;
                    dataType = function.DataType;
                    dbType = function.DbType;
                }
                else
                {
                    dataType = typeof(object);
                    dbType = DbType.Object;
                }
            }
            else
            {
                dataType = typeof(object);
                dbType = DbType.Object;
            }
        }

        #endregion

        #region ContainsItemWithAlias.

        internal static bool ContainsItemWithAlias(IEnumerable list, string itemAlias)
        {
            foreach (ISqlItem item in list)
            {
                if (item.Alias == itemAlias)
                    return true;
            }

            return false;
        }

        #endregion
    }
}